package dao;

import interfaceDAO.IDAOUser;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import domain.HibernateUtil;
import domain.User;

class DAOUser implements IDAOUser {

	public User addUser(String firstName, String lastName,String email, String pseudo,
			String password) {

		Session session = HibernateUtil.newSession();
		session.beginTransaction();
		try {

			User newUser = new User();

			newUser.setFirstName(firstName);
			newUser.setLastName(lastName);
			newUser.setPseudo(pseudo);
			newUser.setPassword(password);
			newUser.setEmail(email);
			

			session.save(newUser);
			session.getTransaction().commit();

			return newUser;
		} finally {
			HibernateUtil.closeSession(session);
		}
	}

	public Boolean isUser(String pseudo, String password) {

		Session session = HibernateUtil.newSession();
		session.beginTransaction();
		try {
			Criteria selectCriteria = session.createCriteria(User.class);

			selectCriteria.add(Restrictions.eq("pseudo", pseudo)).add(
					Restrictions.eq("password", password));
			List<?> res = selectCriteria.list();

			if ((res == null) || (res.isEmpty())) {
				return false;
			} else {
				return true;
			}
		} finally {
			HibernateUtil.closeSession(session);
		}
	}

	@Override
	public Boolean deleteUser(String pseudo) {

		Session session = HibernateUtil.newSession();
		session.beginTransaction();
		try {

			User user = getUser(pseudo);
			if (user != null) {
				session.delete(user);
				session.getTransaction().commit();

				return true;
			} else {
				return false;
			}

		} finally {
			HibernateUtil.closeSession(session);
		}
	}

	public User getUser(String pseudo) {

		Session session = HibernateUtil.newSession();
		session.beginTransaction();
		try {
			User user = null;
			Criteria selectCriteria = session.createCriteria(User.class);

			selectCriteria.add(Restrictions.eq("pseudo", pseudo));
			List<?> res = selectCriteria.list();

			if (res != null && !res.isEmpty()) {
				user = (User) res.get(0);
			}
			return user;

		} finally {
			HibernateUtil.closeSession(session);
		}
	}
}